import React, { useEffect, useState, useMemo } from 'react';
import { Modal, Spin, message } from 'antd';
import { keyBy, isPlainObject } from 'lodash';

import { queryStaffRelativeKeyList, payrollPrint, saveStaffPrint } from '@/services/salaryManage/salaryCalculate';
import { getCompanyDetail } from '@/services/salaryManage/salaryCommon';

import { isSuccess } from '@/utils/request';
import Setting from './Setting';
import Preview from './Preview';
import styles from './index.less';

const MAX_CHECKED_NUMBER = 5;
const PayslipSettingModal = ({ visible, organizationCode, year, month, onCancel, onOk }) => {
    const [loading, setLoading] = useState(false);
    const [checkedList, setCheckedList] = useState([]);
    const [allList, setAllList] = useState([]);
    const [previewModel, setPreviewModel] = useState({});
    const [companyInfo, setCompanyInfo] = useState({});

    const handleCheckedChange = event => {
        if (event.target.checked) {
            if (checkedList.length < MAX_CHECKED_NUMBER) {
                setCheckedList([...checkedList, event.target.value]);
                return;
            }
            message.warn(`最多选择${MAX_CHECKED_NUMBER}个`);
        } else {
            setCheckedList(checkedList.filter(item => item !== event.target.value));
        }
    };

    const handleOk = () => {
        saveStaffPrint({
            organizationCode,
            staffInfoIdList: checkedList
        }).then(response => {
            if (isSuccess(response)) {
                message.success('保存成功');
                onOk();
            } else {
                message.error(response.msg);
            }
        });
    };

    const checkedModelList = useMemo(() => {
        if (allList?.length > 0 && checkedList?.length > 0) {
            const allKeyMap = keyBy(allList, 'key');
            return checkedList.map(checkedValue => ({
                [allKeyMap[checkedValue].key]: !isPlainObject(allKeyMap[checkedValue].defaultValue)
                    ? allKeyMap[checkedValue].defaultValue
                    : ''
            }));
        }
        return [];
    }, [allList, checkedList]);

    useEffect(() => {
        if (organizationCode && year && month) {
            setLoading(true);
            Promise.all([
                // 员工信息类型 1：员工基本属性 2：员工OFFER属性
                queryStaffRelativeKeyList(organizationCode, 3),
                payrollPrint({ organizationCode, year, month }),
                getCompanyDetail(organizationCode)
            ])
                .then(([staffInfoRes, printInfoRes, companyInfoRes]) => {
                    let selectedStaffList = [];
                    if (isSuccess(staffInfoRes)) {
                        setAllList(staffInfoRes.data);

                        if (staffInfoRes.data) {
                            selectedStaffList = selectedStaffList.concat(
                                staffInfoRes.data.filter(item => item.isSelected === '1').map(item => item.key)
                            );
                        }
                    }

                    if (isSuccess(printInfoRes)) {
                        const viewModel = printInfoRes.data;
                        setPreviewModel(viewModel);

                        if (viewModel?.salaryItemStaffInfoList?.length > 0) {
                            selectedStaffList = selectedStaffList.concat(
                                viewModel?.salaryItemStaffInfoList.map(item => item.id)
                            );
                        }
                    }

                    if (isSuccess(companyInfoRes)) {
                        setCompanyInfo(companyInfoRes.data);
                    }

                    if (selectedStaffList.length > 0) {
                        setCheckedList(selectedStaffList);
                    }
                })
                .finally(() => setLoading(false));
        }
    }, [organizationCode, year, month]);

    return (
        <Modal
            visible={visible}
            title="薪资条打印设置"
            width={1296}
            onCancel={onCancel}
            onOk={handleOk}
            style={{ top: 50 }}
            bodyStyle={{ padding: '30px 36px' }}
        >
            <Spin spinning={loading}>
                <div className={styles.payslipSettingModal}>
                    <Setting
                        allList={allList}
                        checkedList={checkedList}
                        onChange={handleCheckedChange}
                        editable={!checkedList || checkedList.length < MAX_CHECKED_NUMBER}
                    />
                    <Preview model={previewModel} checkedStaffInfo={checkedModelList} companyInfo={companyInfo} />
                </div>
            </Spin>
        </Modal>
    );
};

export default PayslipSettingModal;
